<template>
  <div class="cart-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-section">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>购物车</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <!-- 购物车标题 -->
    <div class="cart-header">
      <h1 class="cart-title">我的购物车</h1>
      <div class="cart-summary">共 {{ cartItems.length }} 件商品</div>
    </div>
    
    <!-- 购物车内容 -->
    <div v-if="!loading" class="cart-content">
      <!-- 购物车为空 -->
      <div v-if="cartItems.length === 0" class="empty-cart">
        <div class="empty-icon">
          <el-icon><ShoppingCart /></el-icon>
        </div>
        <div class="empty-text">购物车还是空的，快去选购商品吧！</div>
        <el-button type="primary" @click="goShopping" class="go-shopping-btn">
          去购物
        </el-button>
      </div>
      
      <!-- 购物车列表 -->
      <div v-else class="cart-list">
        <!-- 表头 -->
        <div class="cart-table-header">
          <div class="table-col col-select">
            <el-checkbox v-model="allSelected" @change="handleSelectAll">全选</el-checkbox>
          </div>
          <div class="table-col col-info">商品信息</div>
          <div class="table-col col-price">单价</div>
          <div class="table-col col-quantity">数量</div>
          <div class="table-col col-total">小计</div>
          <div class="table-col col-action">操作</div>
        </div>
        
        <!-- 购物车商品列表 -->
        <div class="cart-items-list">
          <CartItem 
            v-for="item in cartItems" 
            :key="item.id"
            :item="item"
            :selected="selectedItems.includes(item.id)"
            @select="handleSelectItem"
            @update-quantity="handleUpdateQuantity"
            @delete="handleDeleteItem"
          />
        </div>
        
        <!-- 结算栏 -->
        <div class="cart-footer">
          <div class="footer-left">
            <div class="select-all">
              <el-checkbox v-model="allSelected" @change="handleSelectAll">全选</el-checkbox>
            </div>
            <el-button type="text" @click="handleDeleteSelected" class="delete-selected-btn">
              删除选中商品
            </el-button>
            <el-button type="text" @click="handleClearCart" class="clear-cart-btn">
              清空购物车
            </el-button>
          </div>
          
          <div class="footer-right">
            <div class="total-info">
              <div class="total-text">合计：</div>
              <div class="total-price">
                <span class="currency">¥</span>
                <span class="price-number">{{ totalPrice }}</span>
              </div>
              <div class="total-count">已选 {{ selectedCount }} 件商品</div>
            </div>
            <el-button 
              type="primary" 
              @click="handleCheckout"
              :disabled="selectedCount === 0"
              class="checkout-btn"
            >
              结算
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <el-loading v-loading="loading" element-loading-text="加载中..." />
    </div>
    
    <!-- 猜你喜欢 -->
    <div v-if="!loading && cartItems.length > 0 && recommendedProducts.length > 0" class="recommended-products">
      <div class="recommended-title">猜你喜欢</div>
      <div class="recommended-list">
        <ProductCard 
          v-for="product in recommendedProducts" 
          :key="product.id"
          :product="product"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '../../store/modules/cart'
import { useProductStore } from '../../store/modules/product'
import { useUserStore } from '../../store/modules/user'
import { ArrowRight, ShoppingCart } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatNumber } from '../../utils/helper'
import CartItem from '../../components/cart/CartItem.vue'
import ProductCard from '../../components/product/ProductCard.vue'

const router = useRouter()
const cartStore = useCartStore()
const productStore = useProductStore()
const userStore = useUserStore()

// 响应式数据
const loading = ref(true)
const cartItems = ref([])
const selectedItems = ref([])
const recommendedProducts = ref([])

// 计算属性：是否全选
const allSelected = computed({
  get() {
    return cartItems.value.length > 0 && selectedItems.value.length === cartItems.value.length
  },
  set(value) {
    if (value) {
      selectedItems.value = cartItems.value.map(item => item.id)
    } else {
      selectedItems.value = []
    }
  }
})

// 计算属性：选中的商品数量
const selectedCount = computed(() => {
  return selectedItems.value.length
})

// 计算属性：总价
const totalPrice = computed(() => {
  return selectedItems.value.reduce((total, itemId) => {
    const item = cartItems.value.find(i => i.id === itemId)
    return total + (item ? (item.price * item.quantity) : 0)
  }, 0)
})

// 去购物
const goShopping = () => {
  router.push('/')
}

// 处理全选
const handleSelectAll = () => {
  // 由计算属性的setter处理
}

// 处理选择商品
const handleSelectItem = (itemId, isSelected) => {
  if (isSelected) {
    if (!selectedItems.value.includes(itemId)) {
      selectedItems.value.push(itemId)
    }
  } else {
    const index = selectedItems.value.indexOf(itemId)
    if (index > -1) {
      selectedItems.value.splice(index, 1)
    }
  }
}

// 处理更新商品数量
const handleUpdateQuantity = async (itemId, quantity) => {
  try {
    await cartStore.updateCartItemQuantity(itemId, quantity)
    // 重新加载购物车数据
    await loadCartItems()
  } catch (error) {
    ElMessage.error('更新数量失败：' + error.message)
  }
}

// 处理删除商品
const handleDeleteItem = async (itemId) => {
  ElMessageBox.confirm(
    '确定要删除该商品吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await cartStore.deleteCartItem(itemId)
      // 从选中列表中移除
      const index = selectedItems.value.indexOf(itemId)
      if (index > -1) {
        selectedItems.value.splice(index, 1)
      }
      // 重新加载购物车数据
      await loadCartItems()
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败：' + error.message)
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理删除选中商品
const handleDeleteSelected = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择要删除的商品')
    return
  }
  
  ElMessageBox.confirm(
    '确定要删除选中的商品吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await cartStore.deleteCartItems(selectedItems.value)
      selectedItems.value = []
      // 重新加载购物车数据
      await loadCartItems()
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败：' + error.message)
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理清空购物车
const handleClearCart = async () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车已经是空的')
    return
  }
  
  ElMessageBox.confirm(
    '确定要清空购物车吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await cartStore.clearCart()
      selectedItems.value = []
      // 重新加载购物车数据
      await loadCartItems()
      ElMessage.success('购物车已清空')
    } catch (error) {
      ElMessage.error('清空失败：' + error.message)
    }
  }).catch(() => {
    // 用户取消清空
  })
}

// 处理结算
const handleCheckout = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择要结算的商品')
    return
  }
  
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  // 获取选中的购物车商品
  const selectedCartItems = cartItems.value.filter(item => 
    selectedItems.value.includes(item.id)
  )
  
  // 设置待结算商品
  cartStore.setCheckoutItems(selectedCartItems)
  
  // 跳转到结算页面
  router.push('/order/checkout')
}

// 加载购物车数据
const loadCartItems = async () => {
  loading.value = true
  try {
    // 模拟API调用，实际项目中替换为真实API
    // const data = await cartStore.getCartItems()
    // cartItems.value = data
    
    // 模拟购物车数据
    cartItems.value = generateMockCartItems()
    
    // 默认选中所有商品
    selectedItems.value = cartItems.value.map(item => item.id)
    
    // 加载推荐商品
    await loadRecommendedProducts()
  } catch (error) {
    ElMessage.error('加载购物车失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 加载推荐商品
const loadRecommendedProducts = async () => {
  try {
    // 模拟API调用，实际项目中替换为真实API
    // const data = await productStore.getRecommendedProducts()
    // recommendedProducts.value = data
    
    // 模拟推荐商品数据
    recommendedProducts.value = generateMockRecommendedProducts()
  } catch (error) {
    console.error('加载推荐商品失败：', error)
  }
}

// 生成模拟购物车数据
const generateMockCartItems = () => {
  return [
    {
      id: 1,
      productId: 1,
      name: '超级智能手机 Pro Max',
      image: '/product/hot1.png',
      price: 6999,
      quantity: 1,
      specs: { '颜色': '暗夜黑', '内存': '8GB+256GB' }
    },
    {
      id: 2,
      productId: 3,
      name: '智能手表 Series 7',
      image: '/product/hot3.png',
      price: 2199,
      quantity: 1,
      specs: { '颜色': '深空灰', '尺寸': '45mm' }
    },
    {
      id: 3,
      productId: 4,
      name: '无线蓝牙耳机 Pro',
      image: '/product/hot4.png',
      price: 1299,
      quantity: 2,
      specs: { '颜色': '白色' }
    },
    {
      id: 4,
      productId: 10,
      name: '无线充电器 15W快充',
      image: '/product/discount2.png',
      price: 129,
      quantity: 1,
      specs: { '颜色': '黑色' }
    }
  ]
}

// 生成模拟推荐商品数据
const generateMockRecommendedProducts = () => {
  return [
    {
      id: 5,
      name: '全新旗舰手机 Ultra',
      image: '/product/new1.png',
      price: 8999,
      originalPrice: 9999,
      rating: 4.9,
      reviewCount: 123,
      salesVolume: '1000+'
    },
    {
      id: 6,
      name: '便携投影仪 Mini',
      image: '/product/new2.png',
      price: 3299,
      originalPrice: 3699,
      rating: 4.8,
      reviewCount: 89,
      salesVolume: '800+'
    },
    {
      id: 7,
      name: '智能空气净化器',
      image: '/product/new3.png',
      price: 1999,
      originalPrice: 2299,
      rating: 4.7,
      reviewCount: 67,
      salesVolume: '500+'
    },
    {
      id: 8,
      name: '机械键盘 RGB背光',
      image: '/product/new4.png',
      price: 899,
      originalPrice: 1099,
      rating: 4.6,
      reviewCount: 45,
      salesVolume: '300+'
    }
  ]
}

// 组件挂载时加载数据
onMounted(() => {
  loadCartItems()
})
</script>

<style scoped>
.cart-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

/* 面包屑导航 */
.breadcrumb-section {
  margin: 20px 0;
}

/* 购物车标题 */
.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.cart-title {
  font-size: $font-size-xxl;
  color: $text-color;
  font-weight: bold;
  margin: 0;
}

.cart-summary {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

/* 购物车内容 */
.cart-content {
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
  padding: 0;
  margin-bottom: 30px;
}

/* 购物车为空 */
.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  padding: 40px;
}

.empty-icon {
  font-size: 80px;
  color: $text-color-placeholder;
  margin-bottom: 20px;
}

.empty-text {
  font-size: $font-size-base;
  color: $text-color-secondary;
  margin-bottom: 20px;
}

.go-shopping-btn {
  padding: 10px 30px;
  font-size: $font-size-base;
}

/* 购物车列表 */
.cart-list {
  width: 100%;
}

/* 表头 */
.cart-table-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background-color: $fill-color;
  border-bottom: 1px solid $border-color;
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.table-col {
  display: flex;
  align-items: center;
}

.col-select {
  width: 80px;
}

.col-info {
  flex: 1;
  min-width: 300px;
}

.col-price {
  width: 120px;
  justify-content: center;
}

.col-quantity {
  width: 180px;
  justify-content: center;
}

.col-total {
  width: 120px;
  justify-content: center;
  color: $danger-color;
  font-weight: 500;
}

.col-action {
  width: 100px;
  justify-content: center;
}

/* 购物车商品列表 */
.cart-items-list {
  /* 由CartItem组件填充 */
}

/* 结算栏 */
.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-top: 1px solid $border-color;
  background-color: #fff;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.select-all {
  font-size: $font-size-sm;
  color: $text-color;
}

.delete-selected-btn,
.clear-cart-btn {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.delete-selected-btn:hover,
.clear-cart-btn:hover {
  color: $danger-color;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 30px;
}

.total-info {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.total-text {
  font-size: $font-size-base;
  color: $text-color;
}

.total-price {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.total-price .currency {
  font-size: $font-size-lg;
  color: $danger-color;
}

.total-price .price-number {
  font-size: $font-size-xxl;
  color: $danger-color;
  font-weight: bold;
}

.total-count {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.checkout-btn {
  padding: 12px 36px;
  font-size: $font-size-base;
  background-color: $danger-color;
  border-color: $danger-color;
}

.checkout-btn:hover {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

.checkout-btn:disabled {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: $text-color-placeholder;
}

/* 加载状态 */
.loading-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
  margin-bottom: 30px;
}

/* 猜你喜欢 */
.recommended-products {
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
  padding: 30px;
  margin-bottom: 30px;
}

.recommended-title {
  font-size: $font-size-xl;
  color: $text-color;
  font-weight: 500;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid $primary-color;
}

.recommended-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .recommended-list {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 992px) {
  .cart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .cart-table-header {
    padding: 12px 16px;
  }
  
  .col-info {
    min-width: 200px;
  }
  
  .col-quantity {
    width: 150px;
  }
  
  .footer-right {
    gap: 20px;
  }
  
  .recommended-list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .cart-container {
    padding: 0 10px;
  }
  
  .cart-content {
    padding: 0;
  }
  
  .cart-table-header {
    font-size: $font-size-xs;
  }
  
  .col-select {
    width: 60px;
  }
  
  .col-info {
    min-width: 150px;
  }
  
  .col-price,
  .col-total {
    width: 80px;
  }
  
  .col-quantity {
    width: 120px;
  }
  
  .col-action {
    width: 60px;
  }
  
  .cart-footer {
    flex-direction: column;
    align-items: stretch;
    gap: 20px;
  }
  
  .footer-left,
  .footer-right {
    justify-content: center;
  }
  
  .total-info {
    justify-content: center;
  }
  
  .recommended-products {
    padding: 20px 16px;
  }
  
  .recommended-list {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .empty-cart {
    padding: 20px;
  }
  
  .empty-icon {
    font-size: 60px;
  }
  
  .cart-table-header {
    padding: 8px 12px;
  }
  
  .footer-left {
    flex-direction: column;
    gap: 10px;
  }
  
  .total-price .price-number {
    font-size: $font-size-xl;
  }
  
  .checkout-btn {
    width: 100%;
  }
}
</style>